package LeetCode;

public class LC_529_Minesweeper {

    public static void main(String[] args) {

    }

    public class Solution {
        int[][] dirs = {{1, 0}, {1, 1}, {1, -1}, {-1, 0}, {-1, 1}, {-1, -1}, {0, 1}, {0, -1}};

        public char[][] updateBoard(char[][] board, int[] click) {
            if (board == null || board.length == 0) return board;
            int i = click[0];
            int j = click[1];
            if (board[i][j] == 'M') {
                board[i][j] = 'X';
                return board;
            }
            update(board, i, j);
            return board;
        }

        private void update(char[][] board, int i, int j) {
            if (board[i][j] != 'E') return;
            int cnt = 0;
            for (int[] dir : dirs) {
                int row = dir[0] + i;
                int col = dir[1] + j;
                if (row >= 0 && row < board.length && col >= 0 && col < board[0].length && board[row][col] == 'M')
                    cnt++;
            }
            board[i][j] = '*';
            if (cnt == 0) {
                board[i][j] = 'B';
                for (int[] dir : dirs) {
                    int row = dir[0] + i;
                    int col = dir[1] + j;
                    if (row >= 0 && row < board.length && col >= 0 && col < board[0].length)
                        update(board, row, col);
                }
            } else
                board[i][j] = (char) (cnt + '0');
        }
        
    }
}